<template>
  	<div class="goodsStandards">
    	<div id="form-wrapper">
      		<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="规格名称" prop="name">
					<el-input v-model="ruleForm.name" placeholder="请输入规格名称"></el-input>
				</el-form-item>
				<el-form-item label="价格" prop="price">
					<el-input v-model="ruleForm.price" placeholder="请输入价格">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				
        		<el-form-item label="区间价格">
					<el-button type="primary" @click="interval_show=true">添加</el-button>
					<div class="interval_list">
						<div class="items" v-for="(item,index) in ruleForm.m_price" :key="index">
							<el-input size="mini" readonly class="item" placeholder="数量" v-model="item.num" clearable></el-input>
							<el-input size="mini" readonly class="item" placeholder="价格" v-model="item.price" clearable></el-input>
							<div class="del">
								<i class="el-icon-delete" @click="del_item(index)"></i>
							</div>
						</div>	
					</div>
				</el-form-item>
        		<el-form-item label="库存" prop="stock">
          			<el-input v-model="ruleForm.stock" type="number" placeholder="请输入库存"></el-input>
        		</el-form-item>
        		<el-form-item label=" 规格图片 (比例 1:1)" prop="titleFileList">
          			<el-upload
						accept=".png, .jpeg, .jpg"
						:action="$api + '/v1/upload/image'"
						list-type="picture-card"
						:before-upload="beforeUpload"
						:on-success="fileSuccess"
						:auto-upload="true"
						:file-list="ruleForm.titleFileList"
						:limit="titleFileMaxCount"
						:class="{'hide': fileToLarge}"
						name="name"
						:data="{'token': token}"
					>
              			<i slot="default" class="el-icon-plus"></i>
              			<div slot="file" slot-scope="{file}">
							<img class="el-upload-list__item-thumbnail" :src="file.url">
                			<span class="el-upload-list__item-actions">
								<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
									<i class="el-icon-zoom-in"></i>
								</span>
								<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
									<i class="el-icon-delete"></i>
								</span>
                			</span>
              			</div>
          			</el-upload>
        		</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm">提交</el-button>
					<el-button @click="close">取消</el-button>
				</el-form-item>
      		</el-form>
    	</div>
   		<el-dialog :visible.sync="dialogPic" :modal-append-to-body="false" :modal="false" custom-class="isX">
      		<img width="100%" :src="dialogImg" alt="">
   		</el-dialog>
		<!--价格区间弹窗-->
		<el-dialog width="30%" title="添加价格区间" :before-close="handleClose" :visible.sync="interval_show" append-to-body >
			<div class="interval">
				<el-input class="item" placeholder="数量" v-model="goods_num" clearable>
					<template slot="append">箱</template>
				</el-input>
				<el-input class="item" placeholder="价格" v-model="goods_price" clearable>
					<template slot="append">元</template>
				</el-input>
				<el-button type="primary" @click="add_interval">确定</el-button>
			</div>
    	</el-dialog>
  	</div>
</template>

<script>
  	import _ from 'lodash'
  	export default {
		name: 'GoodsStandards',
		props: {
			id: String,
			index: Number
		},
    	data() {
      		return {
		  		interval_show:false,
				goods_num:null,
				goods_price:null,
        		token: localStorage.getItem('token'),
        		g_index: this.index,
        		g_id: this.id,
				ruleForm: {
					name: '',
					price: '',
					stock: '',
					m_price:[],
					titleFileList: [],
				},
        		rules: {
					name: [
						{ required: true, message: '请输入类别名称', trigger: 'blur' }
					],
          			price: [
            			{ required: true, message: '请输入商品价格', trigger: 'blur' },
            			{
              				validator(rule, value, callback) {
                				const boolean = new RegExp(/^([1-9]\d{0,8}|0)(\.\d{1,2})?$/).test(value)
								if(!boolean) {
									return callback(new Error('请正确输入商品价格'))
								}
                				return callback()
              				},
              				trigger: 'blur'
            			}
          			],
          			
         		 	stock: [
            			{ required: true, message: '请输入商品库存', trigger: 'blur' },
            			{
              				validator(rule, value, callback) {
                				const boolean = new RegExp(/^[1-9][0-9]*$/).test(value)
								if (!boolean) {
									return callback(new Error('请输入正整数'))
								}
								return callback()
              				},
              				trigger: 'blur'
            			}
          			],
					titleFileList: [
						{ type: 'array', required: true, message: '请上传规格图片' }
					]
        		},
        		titleFileMaxCount: 1,
				dialogImg: '',
				dialogPic: false,
				standardsId: '',
				disabled: false,
				dialogImageUrl: '',
				dialogVisible: false
      		}
    	},
    	watch: {
      		id: {
        		immediate: true,
				handler(val) {
					this.g_id = val
					this._get()
				}
      		},
      		index: {
        		immediate: true,
				handler(val) {
					this.g_index = val
				}
      		}
    	},
    	computed: {
			fileToLarge() {
				return this.ruleForm.titleFileList.length >= this.titleFileMaxCount
			},
			fileIdArr() {
				return this.ruleForm.titleFileList.map((item) => {
					return item.id
				}).toString()
			}
    	},
    	methods: {
			//关闭弹窗
			handleClose(){
				this.goods_price = null
				this.goods_num = null
				this.interval_show = false
			},
			//删除
			del_item(e){
				this.ruleForm.m_price.splice(e,1)
			},
			//确定
			add_interval(){
				if (!this.goods_num) {
					this.$message({
						message: '区间数量格式不正确',
						type: 'warning'
					});
				}else if (!this.goods_price) {
					this.$message({
						message: '区间价格格式不正确',
						type: 'warning'
					});
				}else{
					this.interval_show = false
					let item = {num:this.goods_num,price:this.goods_price}
					this.ruleForm.m_price.push(item)
					this.goods_price = null
					this.goods_num = null
				}
				
			},
      		beforeUpload(file) {
        		const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        		const isLt10M = file.size / 1024 / 1024 < 10
      
        		if (!isJPG) {
          			this.$message.warning('上传头像图片只能是 JPG | PNG 格式!')
        		}
				if (!isLt10M) {
					this.$message.error('上传头像图片大小不能超过 10MB!')
				}
       		 	return isJPG && isLt10M
      		},
      		// 删除图片的事件
			handleRemove(file) {
				this.ruleForm.titleFileList = this.ruleForm.titleFileList.filter((item) => {
					return file.id !== item.id
				})
			},
			handlePictureCardPreview(file) {
				this.dialogImg = file.url;
				this.dialogPic = true;
			},
			fileSuccess(r, file) {
				file.id = file.response.data.id
				this.ruleForm.titleFileList.push({...file})
			},
      		submitForm: _.throttle(function() {
        		this.$refs.ruleForm.validate(async (valid) => {
					if(!valid) {
						return false
					}
          			try{
           		 		let { data: { code, data } } = await this.$axios({
              				url: this.$api + '/v1/gauge/modify',
              				method: 'POST',
							data: {
								id: this.id,
								name: this.ruleForm.name,
								price: this.ruleForm.price,
								m_price: this.ruleForm.m_price,
								stock: this.ruleForm.stock,
								pic_id: this.fileIdArr
							}
            			})
            
            			if(code == 0) {
							let guageData = {
								id: data.id,
								name: data.name,
								m_price: data.m_price,
								price: data.price,
								stock: data.stock,
								imgUrl: this.ruleForm.titleFileList[0].url,
								index: this.g_index
							}
               				this.$emit('guageSuccess', guageData)
               				this.close()
						} else {
							this.$message.warning(data.message)
						}
          			}catch(e){
						this.$message({
							type: 'error',
							message: e
						})
          			}
        		})
      		},2000,{
        		trailing: false
      		}),
      		async _get() {
        		try{
					let { data: { code, data } } = await this.$axios({
						url: this.$api + '/v1/gauge/list' ,
						method: 'GET',
						params: {
							id: this.g_id
						}
					})
          
          			if(code == 0) {
						this.ruleForm.m_price=[]
						this.ruleForm.name = data[0].name
						this.ruleForm.price = data[0].price
						this.ruleForm.m_price = JSON.parse(data[0].m_price).length?JSON.parse(data[0].m_price):[]
						this.ruleForm.stock = data[0].stock
						this.ruleForm.titleFileList = []
						this.ruleForm.titleFileList.push({
							id: data[0].pic_id,
							url: data[0].url
						})
					} else {
						this.$message.warning(data.message)
					}
        		}catch(e){
					this.$message({
						type: 'error',
						message: e
					})
        		}
      		},
			resetForm(formName) {
				this.$refs[formName].resetFields()
			},
			close() {
				this.$emit('close', false)
				// this.resetForm('ruleForm')
			}
    	}
  	}
</script>

<style lang="scss">
	#form-wrapper {
		width: 50%;
		margin: 0 auto;
	}
	.hide .el-upload--picture-card {
		display: none;
	}
	.goodsStandards {
		.isX {
			.el-icon-close:before {
				content: "\E6DB"
			}
		}
	}
	.interval{
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin: 15px 0;
		.item{
			width: 35%;
		}
	}
	.interval_list{
		.items{
			display: flex;
			justify-content: space-between;
			line-height: 28px;
			padding: 10px;
			
			.del{
				font-size: 25px;
			}
			.item{
				width: 40%;
			}
		}
	}
</style>
